package com.mmall.common;

import com.mmall.utils.PropertiesUtil;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * jedis连接池
 */
public class RedisPool {

    private static JedisPool pool;//jedis连接池

    //最大连接数
    private static Integer maxTotal = Integer.parseInt(PropertiesUtil.getProperty("redis.max.total", "20"));

    //最大空闲的实例
    private static Integer maxIdle = Integer.parseInt(PropertiesUtil.getProperty("redis.max.idle", "10"));

    //在pool中最小idle状态的实例
    private static Integer minIdle = Integer.parseInt(PropertiesUtil.getProperty("redis.min.idle", "2"));

    //在borrow一个实例的时候，是否测试，如果赋值为true，则得到的实例时可用的，
    private static boolean testOnBorrow = Boolean.valueOf(PropertiesUtil.getProperty("redis.test.borrow", "true"));

    //在return一个实例的时候，是否测试，如果赋值为true，则得到的实例时可用的，
    private static boolean testOnReturn = Boolean.valueOf(PropertiesUtil.getProperty("redis.test.return", "true"));

    private static String ip = PropertiesUtil.getProperty("redis1.ip");

    private static Integer port = Integer.parseInt(PropertiesUtil.getProperty("redis1.port"));

    private static void initPool() {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(maxTotal);
        config.setMaxIdle(maxIdle);
        config.setMinIdle(minIdle);
        config.setTestOnBorrow(testOnBorrow);
        config.setTestOnReturn(testOnReturn);
        //连接耗尽的是否，是否阻塞，默认为true
        config.setBlockWhenExhausted(true);

        pool = new JedisPool(config, ip, port, 1000 * 2);

    }

    static {
        initPool();
    }

    /**
     * 得到连接池中的jedis
     *
     * @return
     */
    public static Jedis getResource() {
        return pool.getResource();
    }

    //放回到连接池,此方法已弃用，改为jedis.close();
    public static void returnResource(Jedis jedis) {
        pool.returnBrokenResource(jedis);
    }

    public static void main(String[] args) {
        Jedis jedis = getResource();
        jedis.set("zhikey", "zhivalue");
        jedis.close();
        System.out.println(" program is end");
    }

}
